/*
 * Filename TestReportDiseaseConfigServiceImpl.java 2022年05月21日
 * Copyright © Ehome Co.Ltd. All Rgiths Reserved.
 * @author wuyingchao
 */
package com.ehome.poct.core.service.report;

import com.ehome.core.service.AbstractCrudServiceImpl;
import com.ehome.poct.core.api.constant.enums.DiseaseRiskLevel;
import com.ehome.poct.core.api.dto.check.gold.TestReportDiseaseConfigDTO;
import com.ehome.poct.core.api.virtual.TestReportDiseaseConfigService;
import com.ehome.poct.core.api.vo.report.DiseaseCategoryVO;
import com.ehome.poct.core.api.vo.report.DiseaseDtlVO;
import com.ehome.poct.core.factory.DiseaseJudgeFactory;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wyc
 * @since 2022/05/21 14:39
 **/
@Service
@AllArgsConstructor
public class TestReportDiseaseConfigServiceImpl extends AbstractCrudServiceImpl<TestReportDiseaseConfigDTO> implements TestReportDiseaseConfigService {
    private final DiseaseJudgeFactory judgeFactory;

    @Override
    public List<DiseaseCategoryVO> getWithGroupBy(String reportCode, BigDecimal valueA, BigDecimal valueB, Integer timeFlag) {
        // 获取关联病症
        List<TestReportDiseaseConfigDTO> diseases = this.list(new TestReportDiseaseConfigDTO().setReportCode(reportCode).setReactionTime(timeFlag));
        // 分组
        Map<String, List<TestReportDiseaseConfigDTO>> categoryMap =
                diseases.stream().collect(Collectors.groupingBy(TestReportDiseaseConfigDTO::getCategory));
        // 转换
        return categoryMap.entrySet().stream().collect(ArrayList::new, (list, m) -> {
                    final var diseaseDtls = m.getValue().stream()
                            .map(d -> judgeFactory.createJudge(d.getJudgeMode()).judge(valueA, valueB, d))
                            .sorted(Comparator.comparing(DiseaseDtlVO::getLevel))
                            .collect(Collectors.toList());
                    final var expand = diseaseDtls.stream().anyMatch(it -> it.getLevel() != DiseaseRiskLevel.LOW.getLevel());
                    list.add(new DiseaseCategoryVO(m.getKey(), expand, diseaseDtls));
                }
                , ArrayList::addAll
        );
    }
}